<template>
    <span :class="['bc-text-number', attrs.class]">
        <span v-if="prefix" class="bc-text-number-prefix">{{ prefix }}</span>
        {{ value }}
        <span v-if="unit" class="bc-text-number-unit">{{ unit }}</span>
    </span>
</template>

<script setup>
import { computed, useAttrs } from 'vue'

const props = defineProps({
    label: [String, Number],
    delimiter: {
        type: String,
        default: ''
    },
    part: {
        type: Number,
        default: 3
    },
    precision: {
        type: Number,
        default: -1
    },
    scale: {
        type: Number,
        default: 1
    },
    prefix: String,
    unit: String
})

const attrs = useAttrs()

const value = computed(() => {
    if (!/\d/.test(props.label)) return props.label

    let number = Number(props.label) * props.scale

    if (props.precision > -1) {
        const pre = 10 ** props.precision
        number = Math.round(number * pre) / pre
    }

    if (props.delimiter) {
        const reg = new RegExp(`\\d{1,${props.part}}(?=(\\d{${props.part}})+(\\.|$))`, 'gy')
        return number.toString().replace(reg, `$&${props.delimiter}`)
    }

    return number
})
</script>

<style scoped>
.bc-text-number {
    display: inline-block;
    font-family: math, cursive, ui-monospace;
}

.bc-text-number-prefix {
    margin-right: 0.2em;
}

.bc-text-number-unit {
    margin-left: 0.2em;
    font-weight: bold;
}
</style>